<?php

class adminModel extends Model {
	const KEY = 'chongshehui';

	const SHOP_ROLE = 2;

	public function validata($data) {
		$result = Validation::rule(
			array(Validation::isMust($data['name']), '账号不能为空'),
			array(Validation::isMust($data['password']), '密码不能为空'),
			array(Validation::isLength($data['name'], 2, 50), '账号填写有误'),
			array(Validation::isLength($data['password'], 6, 50), '密码长度在6~50位')
		);
		return $result;
	}

	public function getAllStatus() {
		return array(
			1 => '正常', 2 => '停用',
		);
	}

	public function groupByRole() {
		$sql = "select count(admin_id) as total, role_id from a_admin group by role_id";
		$data = [];
		if ($list = $this->query($sql)->fetchAll()) {
			foreach ($list as $row) {
				$data[$row['role_id']] = $row['total'];
			}
		}
		return $data;
	}

	public function login($admin_info) {
		$Encrypt = Doit::singleton('Encrypt');
		$key = md5(Configure::get('security_key') . 'vo');
		$ticket = $Encrypt->encode(implode('\t', array($admin_info['admin_id'], $admin_info['shop_id'], $admin_info['name'], $admin_info['role_id'], Request::getClientIp(), time())), $key);
		$cookie = new Cookie();
		$cookie->set(self::KEY, $ticket, 86400);
		return $ticket;
	}

	public function logout() {
		$cookie = new Cookie();
		$cookie->set(self::KEY, null);
		$cookie->clear();
	}

	public function checkLogin() {
		$cookie = new Cookie();
		$ticket = $cookie->get(self::KEY);
		if (!$ticket) {
			return false;
		}
		$Encrypt = Doit::singleton('Encrypt');
		$admin_info = array(
			'admin_id' => '',
			'shop_id' => '',
			'name' => '',
			'role_id' => '',
			'ip' => '',
			'logintime' => '',
		);
		$key = md5(Configure::get('security_key') . 'vo');
		$idString = $Encrypt->decode($ticket, $key);
		if (isset($idString) && $idString && strpos($idString, '\t')) {
			list($admin_info['admin_id'], $admin_info['shop_id'], $admin_info['name'], $admin_info['role_id'], $admin_info['ip'], $admin_info['logintime']) = explode('\t', $idString);
			if ($admin_info['admin_id'] && $admin_info['name'] && $admin_info['role_id'] &&
				$admin_info['ip'] == Request::getClientIp()) {
				return $admin_info;
			}
		}
		return false;
	}

	public function formateData($data) {
		if (!$data) {
			return array();
		}
		foreach ($data as $key => $value) {
			if (is_array($value)) {
				$data[$key] = $this->formateData($value);
			} else {
				switch ($key) {
				case 'admin_id':
				case 'role_id':
				case 'status':
				case 'pid':
					$data[$key] = (int) $value;
					break;
				default:
					$data[$key] = (string) $value;
				}
			}
		}
		return $data;
	}
}